import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import sys
import os
import numpy as np

# 添加src到路径
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'src'))

from warehouse_management import WarehouseManager
from models.inventory_model import InventoryAnalyzer

# 页面配置已在主应用中设置

# 样式配置
st.markdown("""
<style>
    .metric-card {
        background-color: #f0f2f6;
        padding: 1.5rem;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .warehouse-card {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 1rem;
        margin: 0.5rem 0;
        background-color: #fafafa;
    }
    .location-occupied { background-color: #ffebee; }
    .location-available { background-color: #e8f5e8; }
    .location-reserved { background-color: #fff3e0; }
</style>
""", unsafe_allow_html=True)

# 初始化仓储管理器
@st.cache_resource
def init_warehouse_manager():
    return WarehouseManager()

warehouse_manager = init_warehouse_manager()

# 页面标题
st.markdown('<div style="font-size: 2.5rem; font-weight: bold; color: #1f77b4; text-align: center; margin-bottom: 2rem;">🏪 仓储管理系统</div>', unsafe_allow_html=True)

# 侧边栏功能选择
st.sidebar.title("功能菜单")
function = st.sidebar.selectbox(
    "选择功能",
    ["📊 仓储概览", "🏢 仓库管理", "📍 货位管理", "📦 入库管理", "📤 出库管理", "🔄 库存调拨", "📋 盘点管理"]
)

# 仓储概览
if function == "📊 仓储概览":
    st.header("仓储概览")
    
    # 关键指标
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.metric("总仓库数", "8", "1")
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col2:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.metric("总货位数", "2,456", "128")
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col3:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.metric("货位利用率", "78.5%", "3.2%")
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col4:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.metric("库存总值", "¥45.2M", "¥2.8M")
        st.markdown('</div>', unsafe_allow_html=True)
    
    st.markdown("---")
    
    # 仓库状态概览
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("仓库容量利用率")
        warehouse_data = pd.DataFrame({
            '仓库': ['主仓库', '原料仓', '成品仓', '备件仓', '退货仓', '冷藏仓', '危险品仓', '临时仓'],
            '总容量': [10000, 8000, 12000, 3000, 2000, 1500, 1000, 5000],
            '已使用': [7800, 6200, 9600, 2100, 800, 1200, 750, 2800],
            '利用率': [78, 77.5, 80, 70, 40, 80, 75, 56]
        })
        
        fig_capacity = px.bar(warehouse_data, x='仓库', y=['总容量', '已使用'], 
                             title="仓库容量利用情况", barmode='group')
        st.plotly_chart(fig_capacity, use_container_width=True)
    
    with col2:
        st.subheader("货位状态分布")
        location_status = pd.DataFrame({
            '状态': ['已占用', '可用', '预留', '维护中'],
            '数量': [1928, 428, 78, 22],
            '占比': [78.5, 17.4, 3.2, 0.9]
        })
        
        fig_status = px.pie(location_status, values='数量', names='状态',
                           title="货位状态分布",
                           color_discrete_map={
                               '已占用': '#f44336',
                               '可用': '#4caf50',
                               '预留': '#ff9800',
                               '维护中': '#9e9e9e'
                           })
        st.plotly_chart(fig_status, use_container_width=True)
    
    # 库存周转分析
    st.subheader("库存周转分析")
    
    col1, col2 = st.columns(2)
    
    with col1:
        # 周转率排名
        turnover_data = pd.DataFrame({
            '产品类别': ['电子元件', '原材料A', '包装材料', '成品A', '备件', '原材料B', '成品B', '辅料'],
            '周转率': [12.5, 8.3, 6.7, 5.2, 4.8, 4.1, 3.9, 2.1],
            '库存天数': [29, 44, 54, 70, 76, 89, 94, 174]
        })
        
        fig_turnover = px.bar(turnover_data, x='产品类别', y='周转率', 
                             title="产品类别库存周转率")
        fig_turnover.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_turnover, use_container_width=True)
    
    with col2:
        # 库存天数
        fig_days = px.bar(turnover_data, x='产品类别', y='库存天数',
                         title="产品类别平均库存天数")
        fig_days.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_days, use_container_width=True)
    
    # 今日作业概览
    st.subheader("今日作业概览")
    
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("入库单数", "23", "5")
        st.metric("入库数量", "1,245", "234")
    
    with col2:
        st.metric("出库单数", "45", "8")
        st.metric("出库数量", "2,156", "345")
    
    with col3:
        st.metric("调拨单数", "8", "2")
        st.metric("调拨数量", "456", "67")
    
    with col4:
        st.metric("盘点任务", "3", "1")
        st.metric("异常处理", "2", "-1")

# 仓库管理
elif function == "🏢 仓库管理":
    st.header("仓库管理")
    
    # 仓库列表
    st.subheader("仓库列表")
    
    warehouse_list = pd.DataFrame({
        '仓库编码': ['WH001', 'WH002', 'WH003', 'WH004', 'WH005', 'WH006', 'WH007', 'WH008'],
        '仓库名称': ['主仓库', '原料仓', '成品仓', '备件仓', '退货仓', '冷藏仓', '危险品仓', '临时仓'],
        '仓库类型': ['综合仓', '原料仓', '成品仓', '备件仓', '退货仓', '冷藏仓', '危险品仓', '临时仓'],
        '地址': ['上海市浦东新区', '上海市嘉定区', '上海市青浦区', '上海市松江区', 
               '上海市奉贤区', '上海市宝山区', '上海市金山区', '上海市崇明区'],
        '面积(㎡)': [15000, 12000, 18000, 5000, 3000, 2000, 1500, 8000],
        '货位数': [800, 600, 900, 200, 150, 100, 80, 400],
        '利用率': ['78%', '77.5%', '80%', '70%', '40%', '80%', '75%', '56%'],
        '状态': ['正常', '正常', '正常', '正常', '正常', '正常', '正常', '维护中']
    })
    
    st.dataframe(warehouse_list, use_container_width=True, height=300)
    
    # 仓库详情
    st.subheader("仓库详情")
    
    selected_warehouse = st.selectbox("选择仓库", warehouse_list['仓库名称'].tolist())
    
    if selected_warehouse:
        warehouse_info = warehouse_list[warehouse_list['仓库名称'] == selected_warehouse].iloc[0]
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.info(f"**仓库编码**: {warehouse_info['仓库编码']}")
            st.info(f"**仓库类型**: {warehouse_info['仓库类型']}")
            st.info(f"**仓库面积**: {warehouse_info['面积(㎡)']}㎡")
        
        with col2:
            st.info(f"**货位总数**: {warehouse_info['货位数']}")
            st.info(f"**利用率**: {warehouse_info['利用率']}")
            st.info(f"**状态**: {warehouse_info['状态']}")
        
        with col3:
            st.info(f"**地址**: {warehouse_info['地址']}")
            st.info(f"**管理员**: 张经理")
            st.info(f"**联系电话**: 021-12345678")
    
    # 新增仓库
    st.subheader("新增仓库")
    
    with st.expander("点击展开新增仓库表单"):
        with st.form("add_warehouse_form"):
            col1, col2 = st.columns(2)
            
            with col1:
                wh_code = st.text_input("仓库编码*")
                wh_name = st.text_input("仓库名称*")
                wh_type = st.selectbox("仓库类型", ["综合仓", "原料仓", "成品仓", "备件仓", "退货仓", "冷藏仓", "危险品仓", "临时仓"])
                wh_area = st.number_input("仓库面积(㎡)", min_value=0)
            
            with col2:
                wh_address = st.text_area("仓库地址*")
                wh_manager = st.text_input("管理员")
                wh_phone = st.text_input("联系电话")
                wh_capacity = st.number_input("设计容量", min_value=0)
            
            submitted = st.form_submit_button("添加仓库")
            
            if submitted:
                if wh_code and wh_name and wh_address:
                    st.success(f"仓库 '{wh_name}' 添加成功！")
                else:
                    st.error("请填写所有必填字段")

# 货位管理
elif function == "📍 货位管理":
    st.header("货位管理")
    
    # 仓库选择
    col1, col2 = st.columns(2)
    with col1:
        selected_warehouse = st.selectbox("选择仓库", ['主仓库', '原料仓', '成品仓', '备件仓'])
    with col2:
        search_location = st.text_input("搜索货位", placeholder="输入货位编码")
    
    # 货位布局图（模拟）
    st.subheader("货位布局图")
    
    # 创建模拟的货位布局
    layout_data = []
    for row in range(1, 11):  # 10行
        for col in range(1, 21):  # 20列
            status = np.random.choice(['已占用', '可用', '预留'], p=[0.7, 0.25, 0.05])
            layout_data.append({
                '行': row,
                '列': col,
                '货位编码': f"{selected_warehouse[0]}{row:02d}{col:02d}",
                '状态': status
            })
    
    layout_df = pd.DataFrame(layout_data)
    
    # 创建热力图显示货位状态
    pivot_data = layout_df.pivot(index='行', columns='列', values='状态')
    
    # 将状态转换为数值
    status_map = {'已占用': 2, '预留': 1, '可用': 0}
    pivot_numeric = pivot_data.map(status_map)
    
    fig_layout = px.imshow(pivot_numeric, 
                          title=f"{selected_warehouse} 货位布局图",
                          color_continuous_scale=['green', 'orange', 'red'],
                          aspect='auto')
    
    fig_layout.update_layout(height=400)
    st.plotly_chart(fig_layout, use_container_width=True)
    
    # 货位状态说明
    col1, col2, col3 = st.columns(3)
    with col1:
        st.markdown("🟢 **可用货位**")
    with col2:
        st.markdown("🟠 **预留货位**")
    with col3:
        st.markdown("🔴 **已占用货位**")
    
    # 货位列表
    st.subheader("货位详细信息")
    
    # 筛选条件
    col1, col2, col3 = st.columns(3)
    with col1:
        status_filter = st.selectbox("状态筛选", ['全部', '已占用', '可用', '预留', '维护中'])
    with col2:
        zone_filter = st.selectbox("区域筛选", ['全部', 'A区', 'B区', 'C区', 'D区'])
    with col3:
        type_filter = st.selectbox("类型筛选", ['全部', '普通货位', '重型货位', '冷藏货位', '危险品货位'])
    
    # 货位数据
    location_data = pd.DataFrame({
        '货位编码': [f'A{i:03d}' for i in range(1, 21)],
        '区域': ['A区'] * 10 + ['B区'] * 10,
        '货位类型': ['普通货位'] * 15 + ['重型货位'] * 5,
        '状态': np.random.choice(['已占用', '可用', '预留'], 20),
        '存储产品': [f'产品{chr(65+i%5)}' if np.random.random() > 0.3 else '' for i in range(20)],
        '存储数量': [np.random.randint(0, 1000) if np.random.random() > 0.3 else 0 for i in range(20)],
        '最大容量': [1000] * 15 + [2000] * 5,
        '利用率': [f'{np.random.randint(0, 100)}%' for i in range(20)]
    })
    
    # 应用筛选
    filtered_locations = location_data.copy()
    if status_filter != '全部':
        filtered_locations = filtered_locations[filtered_locations['状态'] == status_filter]
    if zone_filter != '全部':
        filtered_locations = filtered_locations[filtered_locations['区域'] == zone_filter]
    if type_filter != '全部':
        filtered_locations = filtered_locations[filtered_locations['货位类型'] == type_filter]
    
    st.dataframe(filtered_locations, use_container_width=True, height=400)
    
    # 批量操作
    st.subheader("批量操作")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("批量预留"):
            st.success("已批量预留选中货位")
    with col2:
        if st.button("批量释放"):
            st.success("已批量释放选中货位")
    with col3:
        if st.button("导出货位信息"):
            st.success("货位信息已导出")

# 入库管理
elif function == "📦 入库管理":
    st.header("入库管理")
    
    # 功能选择
    tab1, tab2, tab3 = st.tabs(["入库单管理", "新建入库单", "入库统计"])
    
    with tab1:
        st.subheader("入库单列表")
        
        # 筛选条件
        col1, col2, col3 = st.columns(3)
        with col1:
            date_filter = st.date_input("日期筛选", datetime.now())
        with col2:
            status_filter = st.selectbox("状态筛选", ['全部', '待入库', '入库中', '已完成', '异常'])
        with col3:
            warehouse_filter = st.selectbox("仓库筛选", ['全部', '主仓库', '原料仓', '成品仓'])
        
        # 入库单数据
        inbound_data = pd.DataFrame({
            '入库单号': [f'IN{datetime.now().strftime("%Y%m%d")}{i:03d}' for i in range(1, 11)],
            '供应商': ['华东化工', '南方包装', '北京设备', '上海物流', '广州原料'] * 2,
            '仓库': ['主仓库', '原料仓', '成品仓'] * 3 + ['主仓库'],
            '产品数量': np.random.randint(10, 100, 10),
            '入库时间': [datetime.now() - timedelta(hours=i) for i in range(10)],
            '状态': np.random.choice(['待入库', '入库中', '已完成'], 10),
            '操作员': ['张三', '李四', '王五'] * 3 + ['张三'],
            '备注': ['正常入库'] * 8 + ['质检异常', '数量不符']
        })
        
        st.dataframe(inbound_data, use_container_width=True, height=350)
        
        # 操作按钮
        col1, col2, col3 = st.columns(3)
        with col1:
            if st.button("批量确认入库"):
                st.success("已批量确认入库")
        with col2:
            if st.button("打印入库单"):
                st.success("入库单已发送到打印机")
        with col3:
            if st.button("导出入库记录"):
                st.success("入库记录已导出")
    
    with tab2:
        st.subheader("新建入库单")
        
        with st.form("create_inbound_form"):
            col1, col2 = st.columns(2)
            
            with col1:
                supplier = st.selectbox("供应商*", ['华东化工', '南方包装', '北京设备', '上海物流', '广州原料'])
                warehouse = st.selectbox("目标仓库*", ['主仓库', '原料仓', '成品仓', '备件仓'])
                inbound_type = st.selectbox("入库类型*", ['采购入库', '生产入库', '调拨入库', '退货入库'])
            
            with col2:
                expected_date = st.date_input("预计入库日期*", datetime.now())
                operator = st.selectbox("操作员", ['张三', '李四', '王五', '赵六'])
                remarks = st.text_area("备注")
            
            # 入库明细
            st.subheader("入库明细")
            
            # 动态添加入库项
            if 'inbound_items' not in st.session_state:
                st.session_state.inbound_items = [{'product': '', 'quantity': 0, 'location': ''}]
            
            for i, item in enumerate(st.session_state.inbound_items):
                col1, col2, col3, col4 = st.columns([3, 2, 2, 1])
                
                with col1:
                    product = st.selectbox(f"产品{i+1}", ['产品A', '产品B', '产品C', '产品D'], key=f"inbound_product_{i}")
                with col2:
                    quantity = st.number_input(f"数量{i+1}", min_value=0, key=f"inbound_quantity_{i}")
                with col3:
                    location = st.selectbox(f"货位{i+1}", ['A001', 'A002', 'B001', 'B002'], key=f"inbound_location_{i}")
                with col4:
                    if st.button("删除", key=f"inbound_delete_{i}"):
                        st.session_state.inbound_items.pop(i)
                        st.experimental_rerun()
            
            if st.button("添加产品"):
                st.session_state.inbound_items.append({'product': '', 'quantity': 0, 'location': ''})
                st.experimental_rerun()
            
            submitted = st.form_submit_button("创建入库单")
            
            if submitted:
                if supplier and warehouse and expected_date:
                    inbound_number = f"IN{datetime.now().strftime('%Y%m%d%H%M%S')}"
                    st.success(f"入库单 '{inbound_number}' 创建成功！")
                    st.session_state.inbound_items = [{'product': '', 'quantity': 0, 'location': ''}]
                else:
                    st.error("请填写所有必填字段")
    
    with tab3:
        st.subheader("入库统计")
        
        # 时间范围选择
        col1, col2 = st.columns(2)
        with col1:
            start_date = st.date_input("开始日期", datetime.now() - timedelta(days=30))
        with col2:
            end_date = st.date_input("结束日期", datetime.now())
        
        # 统计指标
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            st.metric("入库单数", "234", "23")
        with col2:
            st.metric("入库总量", "12,456", "1,234")
        with col3:
            st.metric("平均处理时间", "2.3小时", "-0.5小时")
        with col4:
            st.metric("异常率", "2.1%", "-0.3%")
        
        # 入库趋势图
        col1, col2 = st.columns(2)
        
        with col1:
            # 每日入库量趋势
            dates = pd.date_range(start=start_date, end=end_date, freq='D')
            daily_inbound = pd.DataFrame({
                '日期': dates,
                '入库量': [400 + i*10 + np.random.randint(-50, 50) for i in range(len(dates))]
            })
            
            fig_daily = px.line(daily_inbound, x='日期', y='入库量', title="每日入库量趋势")
            st.plotly_chart(fig_daily, use_container_width=True)
        
        with col2:
            # 按仓库统计
            warehouse_stats = pd.DataFrame({
                '仓库': ['主仓库', '原料仓', '成品仓', '备件仓'],
                '入库量': [4500, 3200, 2800, 1200]
            })
            
            fig_warehouse = px.bar(warehouse_stats, x='仓库', y='入库量', title="各仓库入库量统计")
            st.plotly_chart(fig_warehouse, use_container_width=True)

# 出库管理
elif function == "📤 出库管理":
    st.header("出库管理")
    
    # 功能选择
    tab1, tab2, tab3 = st.tabs(["出库单管理", "新建出库单", "出库统计"])
    
    with tab1:
        st.subheader("出库单列表")
        
        # 筛选条件
        col1, col2, col3 = st.columns(3)
        with col1:
            date_filter = st.date_input("日期筛选", datetime.now())
        with col2:
            status_filter = st.selectbox("状态筛选", ['全部', '待出库', '拣货中', '已完成', '异常'])
        with col3:
            warehouse_filter = st.selectbox("仓库筛选", ['全部', '主仓库', '原料仓', '成品仓'])
        
        # 出库单数据
        outbound_data = pd.DataFrame({
            '出库单号': [f'OUT{datetime.now().strftime("%Y%m%d")}{i:03d}' for i in range(1, 11)],
            '客户': ['华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团'] * 2,
            '仓库': ['主仓库', '成品仓', '原料仓'] * 3 + ['主仓库'],
            '产品数量': np.random.randint(10, 100, 10),
            '出库时间': [datetime.now() - timedelta(hours=i) for i in range(10)],
            '状态': np.random.choice(['待出库', '拣货中', '已完成'], 10),
            '拣货员': ['张三', '李四', '王五'] * 3 + ['张三'],
            '备注': ['正常出库'] * 8 + ['库存不足', '产品损坏']
        })
        
        st.dataframe(outbound_data, use_container_width=True, height=350)
        
        # 操作按钮
        col1, col2, col3 = st.columns(3)
        with col1:
            if st.button("生成拣货单"):
                st.success("拣货单已生成")
        with col2:
            if st.button("打印出库单"):
                st.success("出库单已发送到打印机")
        with col3:
            if st.button("导出出库记录"):
                st.success("出库记录已导出")
    
    with tab2:
        st.subheader("新建出库单")
        
        with st.form("create_outbound_form"):
            col1, col2 = st.columns(2)
            
            with col1:
                customer = st.selectbox("客户*", ['华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团'])
                warehouse = st.selectbox("出库仓库*", ['主仓库', '原料仓', '成品仓', '备件仓'])
                outbound_type = st.selectbox("出库类型*", ['销售出库', '调拨出库', '生产领料', '报废出库'])
            
            with col2:
                expected_date = st.date_input("预计出库日期*", datetime.now())
                picker = st.selectbox("拣货员", ['张三', '李四', '王五', '赵六'])
                remarks = st.text_area("备注")
            
            # 出库明细
            st.subheader("出库明细")
            
            # 动态添加出库项
            if 'outbound_items' not in st.session_state:
                st.session_state.outbound_items = [{'product': '', 'quantity': 0, 'location': ''}]
            
            for i, item in enumerate(st.session_state.outbound_items):
                col1, col2, col3, col4, col5 = st.columns([3, 2, 2, 2, 1])
                
                with col1:
                    product = st.selectbox(f"产品{i+1}", ['产品A', '产品B', '产品C', '产品D'], key=f"outbound_product_{i}")
                with col2:
                    quantity = st.number_input(f"数量{i+1}", min_value=0, key=f"outbound_quantity_{i}")
                with col3:
                    location = st.selectbox(f"货位{i+1}", ['A001', 'A002', 'B001', 'B002'], key=f"outbound_location_{i}")
                with col4:
                    available = st.text_input(f"可用库存{i+1}", value="100", disabled=True, key=f"outbound_available_{i}")
                with col5:
                    if st.button("删除", key=f"outbound_delete_{i}"):
                        st.session_state.outbound_items.pop(i)
                        st.experimental_rerun()
            
            if st.button("添加产品"):
                st.session_state.outbound_items.append({'product': '', 'quantity': 0, 'location': ''})
                st.experimental_rerun()
            
            submitted = st.form_submit_button("创建出库单")
            
            if submitted:
                if customer and warehouse and expected_date:
                    outbound_number = f"OUT{datetime.now().strftime('%Y%m%d%H%M%S')}"
                    st.success(f"出库单 '{outbound_number}' 创建成功！")
                    st.session_state.outbound_items = [{'product': '', 'quantity': 0, 'location': ''}]
                else:
                    st.error("请填写所有必填字段")
    
    with tab3:
        st.subheader("出库统计")
        
        # 时间范围选择
        col1, col2 = st.columns(2)
        with col1:
            start_date = st.date_input("开始日期", datetime.now() - timedelta(days=30))
        with col2:
            end_date = st.date_input("结束日期", datetime.now())
        
        # 统计指标
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            st.metric("出库单数", "456", "45")
        with col2:
            st.metric("出库总量", "18,234", "2,345")
        with col3:
            st.metric("平均拣货时间", "1.8小时", "-0.2小时")
        with col4:
            st.metric("准确率", "98.5%", "0.5%")
        
        # 出库趋势图
        col1, col2 = st.columns(2)
        
        with col1:
            # 每日出库量趋势
            dates = pd.date_range(start=start_date, end=end_date, freq='D')
            daily_outbound = pd.DataFrame({
                '日期': dates,
                '出库量': [600 + i*15 + np.random.randint(-80, 80) for i in range(len(dates))]
            })
            
            fig_daily = px.line(daily_outbound, x='日期', y='出库量', title="每日出库量趋势")
            st.plotly_chart(fig_daily, use_container_width=True)
        
        with col2:
            # 按客户统计
            customer_stats = pd.DataFrame({
                '客户': ['华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团'],
                '出库量': [3200, 2800, 2400, 2100, 1800]
            })
            
            fig_customer = px.bar(customer_stats, x='客户', y='出库量', title="各客户出库量统计")
            st.plotly_chart(fig_customer, use_container_width=True)

# 库存调拨
elif function == "🔄 库存调拨":
    st.header("库存调拨")
    
    # 功能选择
    tab1, tab2, tab3 = st.tabs(["调拨单管理", "新建调拨单", "调拨统计"])
    
    with tab1:
        st.subheader("调拨单列表")
        
        # 调拨单数据
        transfer_data = pd.DataFrame({
            '调拨单号': [f'TR{datetime.now().strftime("%Y%m%d")}{i:03d}' for i in range(1, 11)],
            '源仓库': ['主仓库', '原料仓', '成品仓'] * 3 + ['主仓库'],
            '目标仓库': ['成品仓', '主仓库', '备件仓'] * 3 + ['原料仓'],
            '产品': [f'产品{chr(65+i%5)}' for i in range(10)],
            '调拨数量': np.random.randint(10, 100, 10),
            '申请时间': [datetime.now() - timedelta(hours=i) for i in range(10)],
            '状态': np.random.choice(['待审批', '已审批', '调拨中', '已完成'], 10),
            '申请人': ['张三', '李四', '王五'] * 3 + ['张三'],
            '审批人': ['经理A', '经理B', '经理C'] * 3 + ['经理A']
        })
        
        st.dataframe(transfer_data, use_container_width=True, height=350)
        
        # 操作按钮
        col1, col2, col3 = st.columns(3)
        with col1:
            if st.button("批量审批"):
                st.success("已批量审批选中调拨单")
        with col2:
            if st.button("执行调拨"):
                st.success("调拨任务已执行")
        with col3:
            if st.button("导出调拨记录"):
                st.success("调拨记录已导出")
    
    with tab2:
        st.subheader("新建调拨单")
        
        with st.form("create_transfer_form"):
            col1, col2 = st.columns(2)
            
            with col1:
                source_warehouse = st.selectbox("源仓库*", ['主仓库', '原料仓', '成品仓', '备件仓'])
                target_warehouse = st.selectbox("目标仓库*", ['主仓库', '原料仓', '成品仓', '备件仓'])
                transfer_reason = st.selectbox("调拨原因*", ['库存平衡', '生产需求', '销售需求', '仓库整理'])
            
            with col2:
                expected_date = st.date_input("预计完成日期*", datetime.now() + timedelta(days=1))
                applicant = st.text_input("申请人", value="当前用户")
                remarks = st.text_area("备注")
            
            # 调拨明细
            st.subheader("调拨明细")
            
            # 动态添加调拨项
            if 'transfer_items' not in st.session_state:
                st.session_state.transfer_items = [{'product': '', 'quantity': 0, 'source_location': '', 'target_location': ''}]
            
            for i, item in enumerate(st.session_state.transfer_items):
                col1, col2, col3, col4, col5 = st.columns([2, 2, 2, 2, 1])
                
                with col1:
                    product = st.selectbox(f"产品{i+1}", ['产品A', '产品B', '产品C', '产品D'], key=f"transfer_product_{i}")
                with col2:
                    quantity = st.number_input(f"数量{i+1}", min_value=0, key=f"transfer_quantity_{i}")
                with col3:
                    source_location = st.selectbox(f"源货位{i+1}", ['A001', 'A002', 'B001', 'B002'], key=f"transfer_source_{i}")
                with col4:
                    target_location = st.selectbox(f"目标货位{i+1}", ['C001', 'C002', 'D001', 'D002'], key=f"transfer_target_{i}")
                with col5:
                    if st.button("删除", key=f"transfer_delete_{i}"):
                        st.session_state.transfer_items.pop(i)
                        st.experimental_rerun()
            
            if st.button("添加产品"):
                st.session_state.transfer_items.append({'product': '', 'quantity': 0, 'source_location': '', 'target_location': ''})
                st.experimental_rerun()
            
            submitted = st.form_submit_button("提交调拨申请")
            
            if submitted:
                if source_warehouse and target_warehouse and source_warehouse != target_warehouse:
                    transfer_number = f"TR{datetime.now().strftime('%Y%m%d%H%M%S')}"
                    st.success(f"调拨单 '{transfer_number}' 提交成功，等待审批！")
                    st.session_state.transfer_items = [{'product': '', 'quantity': 0, 'source_location': '', 'target_location': ''}]
                else:
                    st.error("请检查调拨信息，源仓库和目标仓库不能相同")
    
    with tab3:
        st.subheader("调拨统计")
        
        # 统计指标
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            st.metric("本月调拨单", "89", "12")
        with col2:
            st.metric("调拨总量", "3,456", "456")
        with col3:
            st.metric("平均处理时间", "4.2小时", "-0.8小时")
        with col4:
            st.metric("完成率", "96.5%", "2.1%")
        
        # 调拨流向分析
        col1, col2 = st.columns(2)
        
        with col1:
            # 调拨流向
            flow_data = pd.DataFrame({
                '源仓库': ['主仓库', '原料仓', '成品仓', '备件仓'] * 2,
                '目标仓库': ['成品仓', '主仓库', '备件仓', '主仓库'] * 2,
                '调拨量': [450, 320, 280, 180, 150, 120, 100, 80]
            })
            
            fig_flow = px.bar(flow_data, x='源仓库', y='调拨量', color='目标仓库', title="仓库间调拨流向")
            st.plotly_chart(fig_flow, use_container_width=True)
        
        with col2:
            # 调拨原因分析
            reason_data = pd.DataFrame({
                '调拨原因': ['库存平衡', '生产需求', '销售需求', '仓库整理'],
                '次数': [35, 28, 18, 8]
            })
            
            fig_reason = px.pie(reason_data, values='次数', names='调拨原因', title="调拨原因分析")
            st.plotly_chart(fig_reason, use_container_width=True)

# 盘点管理
elif function == "📋 盘点管理":
    st.header("盘点管理")
    
    # 功能选择
    tab1, tab2, tab3 = st.tabs(["盘点任务", "创建盘点", "盘点报告"])
    
    with tab1:
        st.subheader("盘点任务列表")
        
        # 盘点任务数据
        inventory_tasks = pd.DataFrame({
            '盘点单号': [f'IC{datetime.now().strftime("%Y%m%d")}{i:03d}' for i in range(1, 11)],
            '盘点类型': ['全盘', '抽盘', '循环盘点'] * 3 + ['全盘'],
            '仓库': ['主仓库', '原料仓', '成品仓'] * 3 + ['备件仓'],
            '盘点范围': ['全部货位', 'A区', 'B区', 'C区', '全部货位', 'A区', 'B区', 'C区', '全部货位', 'D区'],
            '计划日期': [datetime.now() + timedelta(days=i) for i in range(10)],
            '状态': ['待执行', '进行中', '已完成', '暂停'] * 2 + ['待执行', '进行中'],
            '盘点员': ['张三', '李四', '王五'] * 3 + ['赵六'],
            '进度': ['0%', '45%', '100%', '30%'] * 2 + ['0%', '60%']
        })
        
        st.dataframe(inventory_tasks, use_container_width=True, height=350)
        
        # 操作按钮
        col1, col2, col3 = st.columns(3)
        with col1:
            if st.button("开始盘点"):
                st.success("盘点任务已开始")
        with col2:
            if st.button("暂停盘点"):
                st.warning("盘点任务已暂停")
        with col3:
            if st.button("完成盘点"):
                st.success("盘点任务已完成")
    
    with tab2:
        st.subheader("创建盘点任务")
        
        with st.form("create_inventory_form"):
            col1, col2 = st.columns(2)
            
            with col1:
                inventory_type = st.selectbox("盘点类型*", ['全盘', '抽盘', '循环盘点', '动态盘点'])
                warehouse = st.selectbox("盘点仓库*", ['主仓库', '原料仓', '成品仓', '备件仓'])
                inventory_range = st.selectbox("盘点范围*", ['全部货位', 'A区', 'B区', 'C区', 'D区', '指定货位'])
            
            with col2:
                planned_date = st.date_input("计划盘点日期*", datetime.now() + timedelta(days=1))
                inventory_person = st.selectbox("盘点员*", ['张三', '李四', '王五', '赵六'])
                supervisor = st.selectbox("监盘人", ['经理A', '经理B', '经理C'])
            
            # 盘点说明
            st.subheader("盘点说明")
            inventory_reason = st.text_area("盘点原因")
            special_requirements = st.text_area("特殊要求")
            
            # 如果选择指定货位，显示货位选择
            if inventory_range == '指定货位':
                st.subheader("指定货位")
                selected_locations = st.multiselect(
                    "选择货位",
                    ['A001', 'A002', 'A003', 'B001', 'B002', 'B003', 'C001', 'C002', 'C003']
                )
            
            submitted = st.form_submit_button("创建盘点任务")
            
            if submitted:
                if inventory_type and warehouse and inventory_range and planned_date and inventory_person:
                    inventory_number = f"IC{datetime.now().strftime('%Y%m%d%H%M%S')}"
                    st.success(f"盘点任务 '{inventory_number}' 创建成功！")
                else:
                    st.error("请填写所有必填字段")
    
    with tab3:
        st.subheader("盘点报告")
        
        # 选择盘点任务
        selected_task = st.selectbox("选择盘点任务", 
                                   [f'IC{datetime.now().strftime("%Y%m%d")}{i:03d}' for i in range(1, 6)])
        
        if selected_task:
            # 盘点结果汇总
            st.subheader("盘点结果汇总")
            
            col1, col2, col3, col4 = st.columns(4)
            with col1:
                st.metric("盘点货位数", "156")
            with col2:
                st.metric("盘点产品种类", "89")
            with col3:
                st.metric("差异货位数", "12")
            with col4:
                st.metric("差异率", "7.7%")
            
            # 盘点差异明细
            st.subheader("盘点差异明细")
            
            difference_data = pd.DataFrame({
                '货位编码': ['A001', 'A015', 'B023', 'B045', 'C012', 'C034'],
                '产品名称': ['产品A', '产品B', '产品C', '产品A', '产品D', '产品E'],
                '账面数量': [100, 250, 180, 320, 150, 200],
                '实盘数量': [98, 255, 175, 315, 155, 195],
                '差异数量': [-2, 5, -5, -5, 5, -5],
                '差异率': ['-2%', '2%', '-2.8%', '-1.6%', '3.3%', '-2.5%'],
                '差异原因': ['自然损耗', '计量误差', '出库未扣减', '盘点错误', '入库未录入', '自然损耗']
            })
            
            st.dataframe(difference_data, use_container_width=True, height=250)
            
            # 差异分析图表
            col1, col2 = st.columns(2)
            
            with col1:
                # 差异类型分布
                reason_stats = difference_data['差异原因'].value_counts().reset_index()
                reason_stats.columns = ['差异原因', '次数']
                
                fig_reason = px.pie(reason_stats, values='次数', names='差异原因', title="差异原因分析")
                st.plotly_chart(fig_reason, use_container_width=True)
            
            with col2:
                # 差异金额影响
                difference_data['单价'] = [50, 30, 80, 50, 120, 90]
                difference_data['差异金额'] = difference_data['差异数量'] * difference_data['单价']
                
                fig_amount = px.bar(difference_data, x='产品名称', y='差异金额', 
                                   title="差异金额影响分析",
                                   color='差异金额',
                                   color_continuous_scale='RdYlGn_r')
                st.plotly_chart(fig_amount, use_container_width=True)
            
            # 处理建议
            st.subheader("处理建议")
            
            suggestions = [
                "对于自然损耗类差异，建议调整损耗率参数",
                "对于计量误差，建议加强计量设备校准",
                "对于系统录入错误，建议完善操作流程",
                "对于盘点错误，建议加强盘点人员培训"
            ]
            
            for i, suggestion in enumerate(suggestions, 1):
                st.info(f"{i}. {suggestion}")
            
            # 导出功能
            col1, col2 = st.columns(2)
            with col1:
                if st.button("导出盘点报告"):
                    st.success("盘点报告已导出")
            with col2:
                if st.button("提交审批"):
                    st.success("盘点报告已提交审批")

# 页脚
st.markdown("---")
st.markdown("**仓储管理系统** | 智能仓储，高效管理")